// src/views/user/AdminList.tsx
import { Table, Space, Button, Popconfirm, Modal, Form, Input, Select, Tree, message } from 'antd'
import { useEffect, useMemo, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';

import {
EditOutlined,
DeleteOutlined
} from '@ant-design/icons'

import { addAdmin, getAdminList, IAdminParams, removeAdmin, updateAdmin } from '../../api/admin';
import menus, { IMenuProps } from '../../router/menu';
import { AxiosResponse } from 'axios';
import { useAppSelector } from '../../store/hooks';

type AdminListProps = {}
// 数据端口
interface DataType {
  adminid: string;
  adminname: number;
  password: string;
  role: number;
  checkedKeys: any[];
}

// 设置添加管理员选择管理权限的接口
interface ITreeData {
  key: string
  title: string
  children?: ITreeData[]
}

// 如果组件不是默认暴露，那么调用的函数放到组件中
function getTreeData(menus: IMenuProps[]) {
  const arr: ITreeData[] = []
  menus.forEach(item => {
    let obj: ITreeData = {
      key: '',
      title: ''
    }
    if (item.children) {
      obj = {
        key: item.keyid,
        title: item.label,
        children: getTreeData(item.children)
      }
    } else {
      obj = {
        key: item.keyid,
        title: item.label,
      }
    }
    arr.push(obj)
  })
  return arr
}

export const AdminList = (props: AdminListProps) => {
  const [adminList, setAdminList] = useState([])
  const [height] = useState(document.body.offsetHeight)

  // 页码
  const [current, setCurrent] = useState(1)
  // 每页显示个数
  const [pageSize, setPageSize] = useState(10)

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      render: (text, record, index) => {
        return <span>{(current - 1) * pageSize + index + 1}</span>
      }
    },
    {
      title: '账户',
      align: 'center',
      dataIndex: 'adminname'
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 'role',
      render: text => {
        return text === 2 ? '超级管理员' : '管理员'
      }
    },
    {
      title: '操作',
      align: 'center',
      render: (text, record, index) => {
        return (
          <Space >
            <Button type="primary" shape="circle" icon={<EditOutlined />}
              onClick={() => {
                setType('update')
                setAddAdminVisible(true)
                form.setFieldsValue({
                  adminname: record.adminname,
                  role: record.role
                })
                console.log('record', record)
                setCheckedKeys(record.checkedKeys)
              }}
            />
            <Popconfirm
              title="确定删除吗?"
              onConfirm={() => {
                removeAdmin({ adminid: record.adminid }).then(() => { // 删除
                  getAdminData() // 重新获取数据 ---- 重置页码以及每页显示个数
                  setCurrent(1)
                  setPageSize(5)
                })
              }}
              onCancel={() => { }}
              okText="确定"
              cancelText="再想想"
            >
              <Button danger shape="circle" icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  // 封装数据请求，之后增删改查使用
  const getAdminData = () => {
    getAdminList().then(res => {
      // console.log(res.data.data);
      setAdminList(res.data.data)
    })
  }

  // 发送请求获取管理员列表，只执行一次
  useEffect(() => {
    getAdminData()
  }, [])
  // 用于区分更新或是增加
  const [type, setType] = useState('add')
  // 添加管理员
  // 函数式组件用法
  const [form] = Form.useForm(); //此处的form若是没有[]下方会报错
  const [addAdminVisible, setAddAdminVisible] = useState(false)

  const treeData = getTreeData(menus) // 获取菜单项数据
  const [checkedKeys, setCheckedKeys] = useState(['0-0'])
  console.log(checkedKeys)
  // 增加
  const onAdd = (values: IAdminParams) => {
    values.checkedKeys = checkedKeys // 追加数据
    console.log(values)
    addAdmin(values).then(() => {
      // 模态框消失，重置表单
      form.setFieldsValue({
        // 重置表单
        adminname: '',
        password: '',
        role: 1
      })
      setCheckedKeys(['0-0']) // 重置权限
      setAddAdminVisible(false) // 模态框消失
      getAdminData() // 请求新的数据
    })
  }

  // 更新
  const onUpdate = (values: IAdminParams) => {
    values.checkedKeys = checkedKeys
    updateAdmin(values).then(() => {
      form.setFieldsValue({
        adminname: '',
        password: '',
        role: 1
      })
      setCheckedKeys(['0-0'])
      setAddAdminVisible(false)
      getAdminData()
    })
  }

  // 批量删除
  // 选中需要删除的数据
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys: any) => { // 点击选中时的数据事件
    setSelectedRowKeys(newSelectedRowKeys)
  }
  const rowSelection: TableRowSelection<DataType> = { // 最左侧选择框选项
    selectedRowKeys,
    onChange: onSelectChange
  };

  const showDeleteMoreBtn = useMemo(() => { // 计算属性 有选中则出现批量删除，没选中不出现
    return selectedRowKeys.length
  }, [selectedRowKeys])

  // console.log('selectedRowKeys', selectedRowKeys)
  const role = useAppSelector(state => state.user.role)

  return (
    <Space direction='vertical' style={{ width: '100%'}}>
    <Space>
      <Button type="primary" onClick={ () => {
        setType('add')
        setAddAdminVisible(true)
      } }>添加管理员</Button>
      { 
      showDeleteMoreBtn > 0 ? <Button type="primary" onClick={ () => {
 
        if (role < 2) { 
          message.warning('暂无权限')
          return
        }
        // 保证所有的数据删除之后再刷新视图
        // 保证所有的数据都操作完，第一时间想到的是 Promise.all()
        // Promise.all 方法中参数为一个数组，数组的元素的返回值都基于 promise
        // 一个页面5给请求，保证都请求完成之后操作,请求结果 分别对应前面的5各请求
        // Promise.all([请求1， 请求2， 请求3，请求4，请求5]).then(result=> {})
        const removeArr: AxiosResponse<any, any>[] = []
        selectedRowKeys.forEach(async item => {
          removeArr.push(await removeAdmin({ adminid: item }))
        })
        Promise.all(removeArr).then((res) => {
          console.log('result', res)
          getAdminData()
        })
      } }>批量删除</Button> : null }
    </Space>
    <Table 
      dataSource={ adminList } 
      columns = { columns } 
      rowKey = 'adminid'
      bordered
      scroll={ { y: height - 330 } }
      pagination = {{
        position: ['bottomRight'],
        current,
        pageSize,
        onChange: (page, pageSize) => {
          setCurrent(page)
          setPageSize(pageSize)
        },
        showTotal: (total) => {
          return <span>共有{total}条数据</span>
        },
        showQuickJumper: true,
        pageSizeOptions: [5, 10, 20, 50]
      }}
      rowSelection={rowSelection}
      />
    <Modal 
      title= { type === 'add' ? "添加管理员" : "更新管理员信息"} 
      open={ addAdminVisible }
      footer = { null }
      onCancel={ () => {
        form.setFieldsValue({
          adminname: '', password: '', role: 1
        })
        setCheckedKeys(['0-0'])
        setAddAdminVisible(false)
      } }
    >
      <Form form = { form }  name="dynamic_rule" onFinish={ type === 'add' ? onAdd : onUpdate } initialValues = {{ role: 1}}>
        <Form.Item
          name="adminname"
          label="管理员账户"
          rules={[
            {
              required: true,
              message: '请输入管理员账户',
            },
          ]}
        >
          <Input placeholder="管理员账户" disabled = { type === 'update'}/>
        </Form.Item>
        {
          type === 'update' ? null : <Form.Item
          name="password"
          label="管理员密码"
          rules={[
            {
              required: true,
              message: '请输入管理员初始密码',
            },
          ]}
        >
          <Input type="password" placeholder="密码" />
        </Form.Item>
        }
        <Form.Item
          name="role"
          label="管理员角色"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Select >
            <Select.Option value={1}>管理员</Select.Option>
            <Select.Option value={2}>超级管理员</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="checkedkeys"
          label="管理员权限"
        >
          <Tree 
            checkable
            defaultExpandAll
            checkedKeys = { checkedKeys }
            treeData = { treeData }
            onCheck = { (checkedKeys: any) => { return setCheckedKeys(checkedKeys);}}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            { type === 'add' ? '添加' : '更新' }
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  </Space>
  )
}
